package com.ypan.monitor.views;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.ypan.monitor.R;
import com.ypan.monitor.osutils.SensorListItem;
import com.ypan.monitor.osutils.Sensors;
import com.ypan.monitor.osutils.Sensors.SensorListener;

public class SensorsAdapter extends BaseAdapter implements SensorListener {

	private Context ctx;
	private ArrayList<SensorListItem> list;

	public SensorsAdapter(Context ctx) {
		this.ctx = ctx;
		this.list = Sensors.getInstance().getItems();
		Sensors.getInstance().setSensorListener(this);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = LayoutInflater.from(ctx).inflate(
				R.layout.list_item_sensors, null);
		TextView name = (TextView) convertView.findViewById(R.id.name_tv);
		TextView vendor = (TextView) convertView.findViewById(R.id.vendor_tv);
		TextView maxRange = (TextView) convertView
				.findViewById(R.id.maxRange_tv);
		TextView mindelay = (TextView) convertView
				.findViewById(R.id.minidelay_tv);
		TextView power = (TextView) convertView.findViewById(R.id.power_tv);
		TextView resolution = (TextView) convertView
				.findViewById(R.id.resolution_tv);
		TextView type = (TextView) convertView.findViewById(R.id.type_tv);
		TextView version = (TextView) convertView.findViewById(R.id.version_tv);
		TextView values = (TextView) convertView.findViewById(R.id.values_tv);

		SensorListItem item = list.get(position);
		name.setText(item.name);
		vendor.setText(item.vendor);
		maxRange.setText("" + item.maxRange);
		mindelay.setText("" + item.mindelay);
		power.setText("" + item.power);
		resolution.setText("" + item.resolution);
		type.setText("" + item.type);
		version.setText("" + item.version);
		if (item.values != null)
			values.setText("V[x,y,z] = " + item.values[0] + "-"
					+ item.values[1] + "-" + item.values[2]);
		return convertView;
	}

	public void update() {
		notifyDataSetChanged();
	}

	private long lasttime = 0;

	@Override
	public void onSensorChanged() {
		long curtime = System.currentTimeMillis();
		if (curtime - lasttime > 10000) {
			notifyDataSetChanged();
			lasttime = curtime;
		}
	}
}
